<template>
	<view class="container">
		<form @submit="submitForm">
			<!-- 微信头像展示 -->
			<view class="avatar-container" @click="handleGetAvatar">
				<image v-if="formData.image" :src="formData.image" class="avatar" @error="handleImageError"></image>
				<text v-else class="avatar-placeholder">*点击获取微信头像</text>
			</view>

			<!-- 微信昵称展示 -->
			<view class="form-item">
				<text class="label">*微信昵称:</text>
				<input type="text" v-model="formData.name" disabled />
			</view>

			<!-- 手机号展示 -->
			<view class="form-item">
				<text class="label">*手机号:</text>
				<input type="text" v-model="formData.tel"  />
				<button v-if="!formData.tel" type="primary" size="mini" open-type="getPhoneNumber"
					@getphonenumber="getPhoneNumber" :loading="phoneLoading">
					获取手机号
				</button>
			</view>

			<!-- 性别选择 -->
			<view class="form-item">
				<text class="label">*性别:</text>
				<radio-group @change="handleSexChange">
					<label class="radio">
						<radio value="1" :checked="formData.sex === 1" /> 男
					</label>
					<label class="radio">
						<radio value="2" :checked="formData.sex === 2" /> 女
					</label>
				</radio-group>
			</view>

			<view class="form-item">
				<text class="label">生日:</text>
				<birthday-picker :default-value="formData.birth" @change="handleBirthChange" class="custom-picker" />
			</view>

			<!-- 地址输入 -->
			<view class="form-item">
				<text class="label">地址:</text>
				<input type="text" v-model="formData.address" placeholder="请输入详细地址" />
			</view>

			<!-- 单位输入 -->
			<view class="form-item">
				<text class="label">单位:</text>
				<input type="text" v-model="formData.company" placeholder="请输入工作单位" />
			</view>

			<!-- 行业输入 -->
			<view class="form-item">
				<text class="label">行业:</text>
				<input type="text" v-model="formData.career" placeholder="请输入所属行业" />
			</view>

			<button form-type="submit" type="primary" :disabled="!formValid" :loading="submitting">
				{{ submitting ? '提交中...' : '提交注册' }}
			</button>
		</form>
	</view>
</template>

<script>
	import {
		mapGetters,
		mapMutations
	} from 'vuex';
	import mixin from '@/pages/login/js/login-page.mixin.js';
	import BirthdayPicker from '@/components/birthday-picker/birthday-picker.vue'
	export default {
		mixins: [mixin],
		components: {
			BirthdayPicker
		},
		data() {
			return {
				formData: {
					chatId: '',
					name: '',
					tel: '',
					image: '',
					sex: null,
					birth: '',
					address: '',
					company: '',
					career: ''
				},
				phoneLoading: false,
				submitting: false,
				canGetAvatar: true,
				openid: '',
				phoneNumber: '',
				session_key: ''
			}
		},
		onReady() {
			;
			wx.login({
				success: (res) => {
					console.log("get user info begion");
					if (res.code) { //微信登录成功 已拿到code
						this.jsCode = res.code //保存获取到的code  

						let params = {
							code: res.code
						};

						this.$api.getOpenId(params).then(res => {
							// 成功处理
							this.openid = res.openid;
							this.formData.chatId = this.openid;
							this.session_key = res.session_key;
							//const unionid = res.data.unionid;
							console.log('OpenID:', this.openid);
							console.log('登录成功:');
						}).catch(res => {
							// 失败进行的操作
							uni.showToast({
								title: "获取用户id失败!",
								duration: 3000
							});
							return;
						});
					}
				}
			})
		},
		computed: {
			formValid() {
				;
				return [
					this.formData.chatId,
					this.formData.name,
					this.formData.tel,
					this.formData.sex !== null,
				].every(Boolean)
			},
			formattedDate() {
				if (!this.birthDate) return ''
				const date = new Date(this.birthDate)
				return `${date.getFullYear()}年${this.pad(date.getMonth() + 1)}月${this.pad(date.getDate())}日`
			}
		},
		methods: {
			// 获取微信头像和基本信息
			async handleGetAvatar() {
				if (!this.canGetAvatar) return

				try {
					const res = await new Promise((resolve, reject) => {
						uni.getUserProfile({
							desc: '用于完善会员信息',
							lang: 'zh_CN',
							success: resolve,
							fail: reject
						})
					})
					if (res && res.userInfo) {
						this.formData = {
							...this.formData,
							name: res.userInfo.nickName,
							image: res.userInfo.avatarUrl
						}
						this.canGetAvatar = false
					}
				} catch (error) {
					console.error('获取用户信息失败:', error)
					uni.showToast({
						title: '需要授权才能继续操作',
						icon: 'none'
					})
				}
			},

			// 获取手机号
			getPhoneNumber(e) {
				if (e.detail.errMsg == "getPhoneNumber:fail user deny") {
					//用户拒绝授权  
					uni.showToast({
						title: "授权失败",
						icon: 'error',
					});

				} else {
					if (!this.session_key) {
						uni.showToast({
							title: "获取授权失败",
							icon: 'error',
						});
					}

					this.encryptedData = e.detail.encryptedData;
					this.iv = e.detail.iv;

					let data = {
						encryptedData: this.encryptedData,
						iv: this.iv,
						code: this.code,
						session_key: this.session_key
					};
					//获取解密后的手机号码
					this.$api.decryptPhone(data).then(res => {
						// 后端返回的用户信息
						this.formData.tel = res.phoneNumber;
						console.log('phoneNumber:', this.formData.tel);
					}).catch(res => {
						// 失败进行的操作
						uni.showToast({
							title: "获取用户id失败!",
							duration: 3000
						});
						return;
					});
				}

			},

			// 性别选择
			handleSexChange(e) {
				this.formData.sex = parseInt(e.detail.value)
			},

			// 生日选择
			handleBirthChange(e) {
				this.formData.birth = e;
			},
			// 清空选择
			clearDate() {
				this.birthDate = null
				this.$refs.birthdayPicker.clear()
			},

			// 获取今日日期字符串
			getTodayString() {
				const today = new Date()
				return `${today.getFullYear()}-${this.pad(today.getMonth() + 1)}-${this.pad(today.getDate())}`
			},

			// 补零函数
			pad(num) {
				return num.toString().padStart(2, '0')
			},

			// 图片加载失败处理
			handleImageError() {
				this.formData.image = '/static/default-avatar.png'
				uni.showToast({
					title: '头像加载失败',
					icon: 'none'
				})
			},

			// 提交表单
			async submitForm() {
				if (!this.formValid || this.submitting) return

				this.submitting = true

				try {
					const payload = {
						...this.formData,
						birth: this.formData.birth,
						created_at: '',
						updated_at: ''
					}

					//获取解密后的手机号码
					this.$api.createMember(payload).then(res => {
						;
						if (res.code === "200") {
							uni.showToast({
								title: '注册成功'
							})
							let loginResult = new Object;
							//用户登录处理
							this.$api.login(this.formData.chatId).then(res => {
								if (!res) {
									// 失败进行的操作
									uni.showToast({
										title: "登录失败!",
										duration: 3000
									});
									return;
								}
								let loginResult = new Object;
								//拿到后台返回数据放入缓存
								res['token'] = "122333333";
								loginResult.userInfo = res;
								//登录后处理
								this.loginSuccess(loginResult);
								uni.showToast({
									title: '登录成功',
									icon: 'success',
								});
								// 这里可以继续处理登录成功后的逻辑，比如跳转页面等
								uni.navigateBack();
							}).catch(res => {
								// 失败进行的操作
								uni.showToast({
									title: "登录失败!",
									duration: 3000
								});
								return;
							});
						} else {
							uni.showToast({
								title: "注册用户失败！",
								duration: 3000
							});
						}
					}).catch(res => {
						;
						// 失败进行的操作
						uni.showToast({
							title: "注册失败！",
							duration: 3000
						});
						return;
					});

				} catch (error) {
					uni.showToast({
						title: error.message,
						icon: 'none'
					})
				} finally {
					this.submitting = false
				}
			}
		},
		onShow() {
			this.canGetAvatar = true
		}
	}
</script>

<style scoped>
	.container {
		padding: 20rpx;
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	.form-item {
		margin: 20rpx 0;
		padding: 20rpx;
		background: #fff;
		border-radius: 12rpx;
		display: flex;
		align-items: center;
	}

	.label {
		width: 140rpx;
		color: #666;
		font-size: 28rpx;
		flex-shrink: 0;
	}

	input {
		flex: 1;
		font-size: 28rpx;
		padding: 10rpx 0;
	}

	.avatar-container {
		width: 160rpx;
		height: 160rpx;
		border-radius: 50%;
		background: #eee;
		margin: 40rpx auto;
		display: flex;
		align-items: center;
		justify-content: center;
		overflow: hidden;
	}

	.avatar {
		width: 100%;
		height: 100%;
	}

	.avatar-placeholder {
		color: #999;
		font-size: 24rpx;
	}

	.radio {
		margin-right: 40rpx;
	}

	.picker {
		color: #333;
		padding: 10rpx 0;
	}

	button[type=primary] {
		margin-top: 40rpx;
		font-size: 32rpx;
		height: 80rpx;
		line-height: 80rpx;
	}

	.input-wrapper {
		display: flex;
		align-items: center;
		padding: 12px;
		border: 1px solid #e5e5e5;
		border-radius: 4px;
		background-color: #fff;
	}

	.label {
		color: #666;
		margin-right: 8px;
	}

	.value {
		flex: 1;
		color: #333;
	}

	uni-icons {
		color: #999;
		margin-left: 8px;
	}

	.uniui-calendar {
		color: #007aff;
	}

	.uni-datetime-picker__container {
		max-height: 60vh;
	}

	.uni-datetime-picker__btn-confirm {
		background-color: #007aff;
	}

	/* 右侧选择器容器 */
	.picker-container {
		flex: 1;
		/* 占据剩余空间 */
		min-width: 0;
		/* 解决flex布局溢出问题 */
	}

	/* 自定义选择器样式 */
	.custom-picker {
		width: 100%;
		/* 宽度自适应 */
	}

	/* 调整已有样式 */
	.birthday-picker {
		height: 300rpx;
		width: 100%;
		/* 新增 */
	}

	.picker-view {
		height: 100%;
		width: 100%;
		/* 新增 */
	}

	.picker-item {
		line-height: 50px;
		text-align: center;
		font-size: 16px;
		/* 新增响应式样式 */
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
</style>